<?php

namespace Sharks\Core\LifeCycle;

use Closure;
use Exception;
use ReflectionMethod;
use Sharks\Core\AppContext;
use Sharks\Core\Cfg\AppConfig;
use Sharks\Core\Exception\RouteResolveException;
use Sharks\Core\Http\Request;
use Sharks\Core\Support\Log\Log;

/**
 * 程序生命周期
 */
class LifePiple {

    private $app;
    private $actionPiple;
    private $moduleLinePiple;

    public function __construct(AppContext $app) {
        $this->app = $app;
        $this->actionPiple = new ActionPiple();
        $this->moduleLinePiple = new ModuleLinePiple();

        $resolvers = ResolverLoader::load(array(DefaultErrorResolver::class));
        foreach ($resolvers as $resolver) {
            ErrorResolver::register($resolver);
        }

    }

    /**
     * 流水线作业
     */
    public function line() {
        $request = $this->app->request();
        $response = $this->app->response();
        try {
            $this->moduleLinePiple->line($request, $response);

            $this->actionPiple->line($request, $response);

            $this->moduleLinePiple->lined($request, $response);
        }
        catch (Exception $e) {
            Log::error($e);
            ErrorResolver::handle($response, $e);
            if (!$response->hasView()) {
                throw $e;//最后由错误处理程序，如whoops处理
            }
        }
        finally {
            // 如果没有异常发生，则渲染结果
            $response->render();
            Log::debug("Response Render Done");
        }
    }

    
}